<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: LanguageController.php 259 2011-07-22 08:44:00Z beimuaihui $
 */



class Qa_QaquestionController extends Baogg_Controller_Action {

	function init() {


	}

	public function list2Action(){
		global $LANG;

		$i=0;
		$output='';
		$fieldmap=array();

		$params=$this->getRequest()->getParams();
		$QaSurveys=new QaSurveys();
		$rs_qa_surveys=$QaSurveys->getOne(@$params['qa_surveys_id']);
		$surveys_name=$rs_qa_surveys[0]['qa_surveys_name'];

		$Qa_Surveys=new Qa_Surveys();
		$rs_qa_survey=$Qa_Surveys->getOne(@$rs_qa_surveys[0]['sid']);
		$survey_id=@$rs_qa_survey[0]['sid'];
		$language=@$rs_qa_survey[0]['language'];

		$Qa_SurveysLanguageSettings=new Qa_SurveysLanguageSettings();
		$rs_qa_surveys_language_settings=$Qa_SurveysLanguageSettings->getList(array('surveyls_survey_id'=>(int)$survey_id,'surveyls_language'=>$language));
		$survey_title=@$rs_qa_surveys_language_settings[0]['surveyls_title'];

		$arr_additioinal_language=explode(" ",@$rs_qa_survey[0]['additional_languages']);

		if(!$survey_id || !$language){
			echo 'Not Exist such survey,please Check!';
			exit;
		}


		/*
		 * Check question type: This question types will be used (all others are separated in the if clause)
		*  5 - 5 Point Choice
		G - Gender
		I - Language Switch
		L - List (Radio)
		M - Multiple Options
		N - Numerical Input
		O - List With Comment
		P - Multiple Options With Comments
		Y - Yes/No
		! - List (Dropdown) )
		*/
		$Qa_Groups=new Qa_Groups();
		$Qa_Questions=new Qa_Questions();
		$Qa_Answers=new Qa_Answers();
		$Qa_QuestionAttributes=new Qa_QuestionAttributes();

		$QaField=new QaField();
		//legacy
		/* $QaFilter=new QaFilter();
		$QaList=new QaList();
		$QaSort=new QaSort();
		$QaChart=new QaChart(); */

		$rs_qa_field=$QaField->getList(array('qa_surveys_id'=>@$params['qa_surveys_id']));
		$arr_qa_field=array();
		foreach((array)$rs_qa_field as $k_field=>$v_field){
			//$rs_qa_filter=$QaFilter->getList(array('qa_field_id'=>$v_field['qa_field_id'],'ordering'=>0));
			$arr_qa_field[$v_field['qa_field_code']]=$v_field ;//($rs_qa_filter?$rs_qa_filter[0]:array())+
		}
		//echo '<pre>';print_r($arr_qa_field);exit;


		//array(array('name'=>'questions','cols'=>array('*'), 'condition'=>'groups.gid=questions.gid and questions.LANGUAGE=\'zh-Hans\' and parent_qid=0'))
		$rs_qa_groups=$Qa_Groups->getList(array('language'=>$language,'sid'=>(int)$survey_id),array('sort'=>'group_order','dir'=>'asc'),null,array('gid','group_name','group_order'));
		$output.='<table class="data-entry-tbl" cellspacing="0"><thead><tr class="survey"><th colspan="6"><h3>'.$surveys_name.'</h3></th></tr>';


		$i_row=0;
		$i_index=0;	
		$output.='<tr><th class="title1">&nbsp;</th><th  class="title2">'.Baogg_Language::get('question_name').'</th><th class="title5">'.Baogg_Language::get('title').'</th><th class="title6">'.Baogg_Language::get('order').'</th><th class="title8">&nbsp;</th><th class="title9">'.Baogg_Language::get('dict_id').'</th></tr></thead>';//'.Baogg_Language::get('is_list').'

		$field_name='id';
		$is_exist=isset($arr_qa_field[$field_name]);
		$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
		$field_checked=$is_exist?" checked='checked' ":'';
		$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
		$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
		$output.='<tr  class="question  row'.(++$i_row %2).'" >';
		$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name'";
		$output .= $field_checked;
		$output .= " />&nbsp;</td>";
		$output.= '<td>'.Baogg_Language::get('survey_id').":</td>";
		/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
		$output.= "<td><input type='text' name='field_value[$field_name]' value='{$field_value_text}' />  </td>"; */
		$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(Baogg_Language::get('survey_id'))),($is_exist?$arr_qa_field[$field_name]:array())));
		$output.="</tr>";

		$field_name='submitdate';
		$is_exist=isset($arr_qa_field[$field_name]);
		$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
		$field_checked=$is_exist?" checked='checked' ":'';
		$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
		$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');


		$output.='<tr  class="question  row'.(++$i_row %2).'" >';
		$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name'";
		$output .= $field_checked;
		$output .= " />&nbsp;</td>";
		$output.= '<td>'.Baogg_Language::get('submitdate').":</td>";
		/* $output.='<td>'. Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
		$output.= "<td><input type='text' name='field_value[$field_name]' value='{$field_value_text}' />  </td>"; */
		$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(Baogg_Language::get('submitdate'))),($is_exist?$arr_qa_field[$field_name]:array())));
		$output.="</tr>";

		$fieldmap["id"]=array("fieldname"=>"id", 'sid'=>$survey_id, 'type'=>"id", "gid"=>"", "qid"=>"", "aid"=>"");
		$fieldmap["submitdate"]=array("fieldname"=>"submitdate", 'type'=>"submitdate", 'sid'=>$survey_id, "gid"=>"", "qid"=>"", "aid"=>"");

		foreach((array)$rs_qa_groups as $v_group){
			//seperator
			$output.='<tr class="row-seperator"><td colspan="6"></td></tr>';
			$output.= "<tr class=\"group\"><td  colspan=\"6\" class=\"row".(++$i_row %2)."\" style=\"width:100%; background-color: #F8F8FF;color: #1D2D45;\"><h3><input type=\"checkbox\" id=\"group_{$survey_id}X{$v_group['gid']}X\" onclick=\"selectQuestionByGroup('{$survey_id}X{$v_group['gid']}X')\" /> {$v_group['group_name']}</h3></div></td></tr>";
			$output.='<tr><th class="title1">&nbsp;</th><th  class="title2">'.Baogg_Language::get('question_name').'</th><th  class="title5">'.Baogg_Language::get('title').'</th><th  class="title6">'.Baogg_Language::get('order').'</th><th class="title8">&nbsp;</th><th class="title9">'.Baogg_Language::get('dict_id').'</th></tr></thead>';   //<th>'.Baogg_Language::get('op'). '.Baogg_Language::get('is_list').'

			$rs_qa_questions=$Qa_Questions->getList(array('gid'=>(int)$v_group['gid'],'parent_qid'=>0,'LANGUAGE'=>$language),array('sort'=>'question_order','dir'=>'asc'));
			foreach($rs_qa_questions as $v){
				$field_name=$_field_name="{$survey_id}X{$v_group['gid']}X{$v['qid']}";


				//get valid field name,create field map
				if($this->getRequest()->isPost()){
					$fieldmap+=$Qa_Questions->genFieldMapByQuestion($v['qid']);
					continue;
				}

				$question_name=strip_tags($v['question']);
				$question_title=strip_tags($v['title']);
				$output.='<tr class="row-seperator"><td colspan="6"></td></tr>';
				$output.='<tr  class="question  row'.(++$i_row %2).'" >';


				switch($v['type']){
					case 'K':// Multiple Numerical,width textbox less,greater
						/* //$output.='<div class="question" style="color:#D2E0F2;">';
						 $rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						 foreach((array)$rs_sub_question as $v_sub){
							$field_name=$v['type'].$field_name.$v_sub['title'];
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name'";
							//@todo if this field is config,then should $output .= " checked='checked'";
							$output .= " />&nbsp;</td>";
							$output.= '<td>'.$question_name.' - '.strip_tags($v_sub['question']).":</td>";
							$output.='<td>'.Qa_Questions::genOp("$field_name").'</td>';
							$output.= "<td><input type='text' name='field_value[$field_name]' value='' /></td> ";
							$output.=Qa_Questions::genAttr($field_name);
							}
							break;
							*/
					case "Q" : // Multiple Short Text

						$output.="<td>{$question_title}</td><td class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span >{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";

						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question as $k_sub=>$v_sub){
							$field_name=$_field_name.$v_sub['title'];
								
							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name'";
							$output .= $field_checked;
							$output .= " />&nbsp;</td>";
							$output.= '<td>'.strip_tags($v_sub['question']).":</td>";
							//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
							//$output.= "<td><input type='text' name='field_value[$field_name]' value='{$field_value_text}' />  </td>";
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;

					case "T" : // Long free text
					case "U" : // Huge free text
						/*$field_name=$field_name;
						 $output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
						 $output.= "<td>{$question_name}: </td>";
						 $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
						 $output.= "<td><input type='text' name='$field_name' value='' /></td>";
						 $output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle()),($is_exist?$arr_qa_field[$field_name]:array())));
						 break; */

							

					case "N" : // Numerical
						/* $output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
						 $output.= "<td>{$question_name}: </td>";
						 $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
						 $output.= "<td><input type='text' name='$field_name' value='' /></td>";
						 $output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle()),($is_exist?$arr_qa_field[$field_name]:array())));
						 break; */
					case "D" :
						/* $field_name=$v['type'].$field_name;
						 $output .= "<td><input type='checkbox'  name='summary[]' value='$field_name'";
						 //@todo if this field is config,then should $output .= " checked='checked'";
						 $output .= " />&nbsp;</td>";
						 $output.= '<td>'.$question_name.BAOGG_LANGUAGE::get('number_start').":<input type='text' name='$field_name[0]' value='' /> ";
						 $output.= BAOGG_LANGUAGE::get('number_end')."<input type='text' name='$field_name[1]' value='' /> <br />";
						 break; */

					case "S" : // Short free text

						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');


						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
						$output.= "<td>{$question_name}: </td>";
						//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
						//$output.= "<td><input type='text' name='field_value[$field_name]' value='{$field_value_text}' /></td>";
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle($question_name)),($is_exist?$arr_qa_field[$field_name]:array())));
						break;

							

					case "5" : // 5 point choice
						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
						$arr_field_value_text=explode(",",$field_value_text);

						$arr_value=range(1,5);
						$arr_option=array_fill(0,count($arr_value),'<option value="%d" %s>%d</option>');
						$arr_selected=array_fill(0,count($arr_value),'');
						$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
						($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));


						$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_value);


						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
						$output.= "<td>{$question_name}: </td>";
						//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
						//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle($question_name)),($is_exist?$arr_qa_field[$field_name]:array())));
						break;
							
					case "G" : // Gender
						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
						$arr_field_value_text=explode(",",$field_value_text);

						$arr_value=array('F','M');
						$arr_label=array_map(array('BAOGG_LANGUAGE','get'),$arr_value);
						//$arr_label=array(BAOGG_LANGUAGE::get('Female'),BAOGG_LANGUAGE::get('Male'));
						$arr_selected=array_fill(0,count($arr_value),'');
						$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
						($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));


						$arr_option=array_fill(0,count($arr_value),'<option value="%s" %s>%s</option>');
						$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_label);

						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
						$output.= "<td>{$question_name}: </td>";
						//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
						//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle($question_name)),($is_exist?$arr_qa_field[$field_name]:array())));
						break;

					case "Y" : // Yes\No
						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
						$arr_field_value_text=explode(",",$field_value_text);

						$arr_value=array('Y','N');
						$arr_label=array_map(array('BAOGG_LANGUAGE','get'),$arr_value);
						$arr_selected=array_fill(0,count($arr_value),'');
						$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
						($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));

						$arr_option=array_fill(0,count($arr_value),'<option value="%s" %s>%s</option>');
						$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_label);


						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
						$output.= "<td>{$question_name}: </td>";
						//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'','multi').'</td>';
						//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle($question_name)),($is_exist?$arr_qa_field[$field_name]:array())));
						break;

					case "I" : // Language
						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
						$arr_field_value_text=explode(",",$field_value_text);

						$arr_value=$arr_additioinal_language;
						$arr_value[]=$language;
						$arr_labels=array();
						$arr_label=array();
						$arr_labels['zh-Hans'] = '&#31616;&#20307;&#20013;&#25991;';
						$arr_labels['zh-Hant-HK'] = '&#32321;&#39636;&#20013;&#25991;&#35486;&#31995;';
						$arr_labels['zh-Hant-TW']='Chinese (Traditional - Taiwan)';
						$arr_labels['en']='English';
						foreach($arr_value as $v_language){
							$arr_label[]=$arr_labels[$v_language];
						}
						$arr_selected=array_fill(0,count($arr_value),'');
						$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
						($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));

						$arr_option=array_fill(0,count($arr_value),'<option value="%s" %s>%s</option>');
						$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_label);

						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
						$output.= "<td>{$question_name}: </td>";
						//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
						//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle($question_name)),($is_exist?$arr_qa_field[$field_name]:array())));
						break;

					case "A" : // ARRAY OF 5 POINT CHOICE QUESTIONS
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\" >&nbsp;&nbsp;<span>{$question_name}</span></td></tr><tr  class=\"question  row".($i_row %2)."\" >";


						//gen options
						$arr_value=range(1,5);
						$arr_option=array_fill_keys($arr_value,'<option value="%d" %s>%d</option>');



						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question as $K_sub=>$v_sub){
							$field_name=$_field_name.$v_sub['title'];
								
							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);
								
							$arr_selected=array_fill(0,count($arr_value),'');
							$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
							($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));
								
							$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_value);
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
							//$output.= "<td>".$question_name.' - '.strip_tags($v_sub['question'])." </td>";
							$output.= '<td>'.strip_tags($v_sub['question']).":</td>";
							//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							($v_sub!=end($rs_sub_question)) && $output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;
							
						//just like above only a different loop
					case "B" : // ARRAY OF 10 POINT CHOICE QUESTIONS

						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";

						//gen options
						$arr_value=range(1,10);
						$arr_option=array_fill_keys($arr_value,'<option value="%d" %s>%d</option>');



						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question as $k_sub=>$v_sub){
							$field_name=$_field_name.$v_sub['title'];

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);

							$arr_selected=array_fill(0,count($arr_value),'');
							$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
							($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));

							$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_value);
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
							//$output.= "<td>".$question_name.' - '.strip_tags($v_sub['question'])." </td>";
							$output.= '<td>'.strip_tags($v_sub['question']).":</td>";
							//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							($v_sub!=end($rs_sub_question)) && $output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;

					case "C" : // ARRAY OF YES\No\$clang->gT("Uncertain") QUESTIONS
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";

						//gen options
						$arr_value=array('Y','U','N');
						$arr_label=array_map(array('BAOGG_LANGUAGE','get'),$arr_value);
						$arr_option=array_fill_keys($arr_value,'<option value="%s" %s>%s</option>');



						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question as $k_sub=>$v_sub){
							$field_name=$_field_name.$v_sub['title'];

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);
								
							$arr_selected=array_fill(0,count($arr_value),'');
							$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
							($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));
								
							$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_label);

								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
							//$output.= "<td>".$question_name.' - '.strip_tags($v_sub['question'])." </td>";
							$output.= '<td>'.strip_tags($v_sub['question']).":</td>";
							//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							($v_sub!=end($rs_sub_question)) && $output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;
						//similiar to the above one
					case "E" : // ARRAY OF Increase/Same/Decrease QUESTIONS
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";


						//gen options
						$arr_value=array('I','S','D');
						$arr_label=array_map(array('BAOGG_LANGUAGE','get'),$arr_value);
						$arr_option=array_fill_keys($arr_value,'<option value="%s" %s>%s</option>');



						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question as $k=>$v_sub){
							$field_name=$_field_name.$v_sub['title'];

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);
								
							$arr_selected=array_fill(0,count($arr_value),'');
							$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
							($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));
								
							$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_label);

								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' /> </td>";
							//$output.= "<td>".$question_name.' - '.strip_tags($v_sub['question'])." </td>";
							$output.= '<td>'.strip_tags($v_sub['question']).":</td>";
							//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							//$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".implode("",$arr_option)."</select></td>";
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							($v_sub!=end($rs_sub_question)) && $output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;

					case ";" : //ARRAY (Multi Flex) (Text)
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span >{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";
						$rs_sub_question_y=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language,'scale_id'=>0),array('sort'=>'question_order','dir'=>'asc'));
						$rs_sub_question_x=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language,'scale_id'=>1),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question_y as $v_sub_y){
							foreach((array)$rs_sub_question_x as $v_sub_x){
								$field_name=$_field_name.$v_sub_y ['title'] . "_" . $v_sub_x ['title'];

								$is_exist=isset($arr_qa_field[$field_name]);
								$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
								$field_checked=$is_exist?" checked='checked' ":'';
								$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
								$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');


								$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} />&nbsp;</td>";
								$output.= '<td>'.strip_tags($v_sub_y['question']).'['.strip_tags($v_sub_x['question']).']'.' - '.$v_sub_y['title'].'/'.$v_sub_x['title'].":</td>";
								//$output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
								//$output.= "<td><input type='text' name='field_value[$field_name]' value='{$field_value_text}' />  </td>";
								$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_y['question']).'|'.strip_tags($v_sub_x['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
								$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

							}

						}
						break;
					case ":" : //ARRAY (Multi Flex) (Numbers)
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";
						$availableattributesarr=questionAttributes();
						if (isset($availableattributesarr[$v['type']]))
						{
							$availableattributes=$availableattributesarr[$v['type']];
							foreach($availableattributes as $attribute){
								$defaultattributes[$attribute['name']]=$attribute['default'];
							}

							$rs_qa_question_attributes=$Qa_QuestionAttributes->getList(array('qid'=>$v['qid']));
							$setattributes=array();
							foreach((array)$rs_qa_question_attributes as $v){
								$setattributes[$row['attribute']]=$row['value'];
							}

							$qidattributes=array_merge($defaultattributes,$setattributes);
						}
						else
						{
							$qidattributes=array();
						}

						//Get qidattributes for this question
						//$qidattributes = getQuestionAttributes ( $flt [0] );
						if (trim ( @$qidattributes ['multiflexible_max'] ) != '' && trim ( @$qidattributes ['multiflexible_min'] ) == '') {
							$maxvalue = @$qidattributes ['multiflexible_max'];
							$minvalue = 1;
						}
						if (trim ( @$qidattributes ['multiflexible_min'] ) != '' && trim ( @$qidattributes ['multiflexible_max'] ) == '') {
							$minvalue = @$qidattributes ['multiflexible_min'];
							$maxvalue = @$qidattributes ['multiflexible_min'] + 10;
						}
						if (trim ( @$qidattributes ['multiflexible_min'] ) == '' && trim ( @$qidattributes ['multiflexible_max'] ) == '') {
							$minvalue = 1;
							$maxvalue = 10;
						}
						if (trim ( @$qidattributes ['multiflexible_min'] ) != '' && trim ( @$qidattributes ['multiflexible_max'] ) != '') {
							if (@$qidattributes ['multiflexible_min'] < @$qidattributes ['multiflexible_max']) {
								$minvalue = @$qidattributes ['multiflexible_min'];
								$maxvalue = @$qidattributes ['multiflexible_max'];
							}
						}
							
						if (trim ( @$qidattributes ['multiflexible_step'] ) != '') {
							$stepvalue = @$qidattributes ['multiflexible_step'];
						} else {
							$stepvalue = 1;
						}
						if (@$qidattributes ['multiflexible_checkbox'] != 0) {
							$minvalue = 0;
							$maxvalue = 1;
							$stepvalue = 1;
						}

						$arr_value=range($minvalue,$maxvalue,$stepvalue);
						$arr_option=array_fill_keys($arr_value,'<option value="%d" %s>%d</option>');


						$rs_sub_question_y=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language,'scale_id'=>0),array('sort'=>'question_order','dir'=>'asc'));
						$rs_sub_question_x=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language,'scale_id'=>1),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question_y as $v_sub_y){
							foreach((array)$rs_sub_question_y as $v_sub_x){
								$field_name=$_field_name.$v_sub_y ['title'] . "_" . $v_sub_x ['title'];

								$is_exist=isset($arr_qa_field[$field_name]);
								$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
								$field_checked=$is_exist?" checked='checked' ":'';
								$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
								$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
								$arr_field_value_text=explode(",",$field_value_text);
									
								$arr_selected=array_fill(0,count($arr_value),'');
								$arr_selected_only=	array_intersect($arr_value, $arr_field_value_text);
								($selected_only_cnt=count($arr_selected_only)) && ($arr_selected+=array_combine(array_keys($arr_selected_only),array_fill(0,$selected_only_cnt,' selected="selected" ')));
								$arr_option=array_map("sprintf",$arr_option,$arr_value,$arr_selected,$arr_value);


								$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name'";
								//@todo if this field is config,then should $output .= " checked='checked'";
								$output .= " />&nbsp;</td>";
								$output.= '<td>'.strip_tags($v_sub_y['question']).'['.strip_tags($v_sub_x['question']).']'.' - '.$v_sub_y['title'].'/'.$v_sub_x['title'].":</td>";
								//$output.='<td>'.Qa_Questions::genOp("$field_name").'</td>';
								//$output.= "<td><select name='field_value[{$field_name}][]' multiple='multiple' rows='5' cols='5'>".implode("",$arr_option)."</select>  </td>";
								$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_y['question']).'|'.strip_tags($v_sub_x['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
								$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

							}

						}
						break;

						/*
						 * For question type "F" and "H" you can use labels.
						* The only difference is that the labels are applied to column heading
						* or rows respectively
						*/
					case "F" : // FlEXIBLE ARRAY
					case "H" : // ARRAY (By Column)
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";
						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));

						$rs_sub_answer=$Qa_Answers->getList(array('qid'=>(int)$v['qid'],'language'=>$language),array('sortorder','code'));
						foreach((array)$rs_sub_question as $v_sub_question){
							$field_name=$_field_name.$v_sub_question ['title'];

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);

								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} />&nbsp;</td>";
							$output.= '<td>'.strip_tags($v_sub_question['question']).":</td>";
							/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							$output.= "<td><select name='field_value[{$field_name}][]' multiple='multiple'>";
							foreach((array)$rs_sub_answer as $v_sub_answer){
								$str_selected=in_array($v_sub_answer['code'],$arr_field_value_text)?'  selected="selected" ':'';
								$output.="<option value=\"{$v_sub_answer['code']}\" {$str_selected}>({$v_sub_answer['code']})".strip_tags($v_sub_answer['answer'])."</option>";
							}
							$output.="</select>  </td>"; */
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_question['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							(!($v_sub_question==end($rs_sub_question) )) &&  $output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;
					case "R" : //RANKING
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";
						$rs_answer=$Qa_Answers->getList(array('qid'=>(int)$v['qid'],'language'=>$language),array('sortorder','code'));
						$count=count($rs_answer);
						for($i = 1; $i <= $count; $i ++) {
							$field_name=$_field_name.$i;

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} />&nbsp;</td>";
							$output.= '<td>'.strip_tags($v['answer']).":</td>";
							/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							$output.= "<td><select name='field_value[{$field_name}][]' multiple='multiple'>";
							foreach((array)$rs_sub_answer as $v_sub_answer){
								$str_selected='';
								if(in_array($v_sub_answer['code'],$arr_field_value_text)){
									$str_selected=' selected="selected" ';
								}
								$output.="<option value=\"{$v_sub_answer['code']}\" {$str_selected}>({$v_sub_answer['code']})".strip_tags($v_sub_answer['answer'])."</option>";
							}
							$output.="</select>  </td>"; */
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v['answer']))),($is_exist?$arr_qa_field[$field_name]:array())));
							$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";
						}
						break;
					case "X" : //This is a boilerplate question and it has no business in this script
						break;

					case "1" : // MULTI SCALE
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";

						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));

						$rs_sub_answer_0=$Qa_Answers->getList(array('qid'=>(int)$v['qid'],'language'=>$language,'scale_id'=>0),array('sortorder','code'));
						$rs_sub_answer_1=$Qa_Answers->getList(array('qid'=>(int)$v['qid'],'language'=>$language,'scale_id'=>1),array('sortorder','code'));

						foreach((array)$rs_sub_question as $v_sub_question){
							$field_name=$_field_name.$v_sub_question ['title'].'#0';

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} />&nbsp;</td>";
							$rs_question_attr=$Qa_QuestionAttributes->getList(array('qid'=>(int)$v['qid'],'attribute'=>'dualscale_headerA'));
							$label_attr=$rs_question_attr[0]['value'];
							$output.= '<td>'.strip_tags($v_sub_question['question']).(' '.$label_attr).":</td>";
							/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							$output.= "<td><select name='field_value[{$field_name}][]' multiple='multiple'>";
							foreach((array)$rs_sub_answer_0 as $v_sub_answer){
								$str_selected='';
								if(in_array($v_sub_answer['code'],$arr_field_value_text)){
									$str_selected=' selected="selected" ';
								}
								$output.="<option value=\"{$v_sub_answer['code']}\" {$str_selected}>({$v_sub_answer['code']})".strip_tags($v_sub_answer['answer'])."</option>";
							}
							$output.="</select>  </td>"; */
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_question['question']).(' '.$label_attr))),($is_exist?$arr_qa_field[$field_name]:array())));
							$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";


							$field_name=$field_name.$v_sub_question ['title'].'#1';
								
							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$arr_field_value_text=explode(",",$field_value_text);
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} />&nbsp;</td>";
							$rs_question_attr=$Qa_QuestionAttributes->getList(array('qid'=>(int)$v['qid'],'attribute'=>'dualscale_headerB'));
							$label_attr=$rs_question_attr[0]['value'];
							$output.= '<td>'.strip_tags($v_sub_question['question']).(' '.$label_attr).":</td>";
							/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
							$output.= "<td><select name='field_value[{$field_name}][]' multiple='multiple'>";
							foreach((array)$rs_sub_answer_1 as $v_sub_answer){
								$str_selected='';
								if(in_array($v_sub_answer['code'],$arr_field_value_text)){
									$str_selected=' selected="selected" ';
								}
								$output.="<option value=\"{$v_sub_answer['code']}\">({$v_sub_answer['code']})".strip_tags($v_sub_answer['answer'])."</option>";
							}
							$output.="</select>  </td>"; */
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_question['question']).(' '.$label_attr))),($is_exist?$arr_qa_field[$field_name]:array())));
							($v_sub_question!=end($rs_sub_question)) && $output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

						}
						break;

					case "P" : //P - Multiple options with comments
					case "M" : //M - Multiple options
						$output.="<td><input type='checkbox' id='group_{$field_name}' onclick='selectQuestionByGroup(\"{$field_name}\")' /></td><td   class=\"parent-question\" colspan=\"5\">&nbsp;&nbsp;<span>{$question_name}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr  class=\"question  row".($i_row %2)."\" >";

						$str_option='';
						$rs_sub_question=$Qa_Questions->getList(array('parent_qid'=>(int)$v['qid'],'language'=>$language),array('sort'=>'question_order','dir'=>'asc'));
						foreach((array)$rs_sub_question as $v_sub_question){
							$field_name=$_field_name.$v_sub_question['title'];

							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							$field_value_checked=$field_value_text=='Y'?' checked="checked" ': '';
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
							$output.= "<td> ".strip_tags($v_sub_question['question']).": </td>";
							/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'check').'</td>';
							$output.= "<td><input type=\"checkbox\" name=\"field_value[{$field_name}]\" value=\"Y\" {$field_value_checked}/></td>"; */
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_question['question']))),($is_exist?$arr_qa_field[$field_name]:array())));
							$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

							if($v['type']=='P'){
								$field_name.='comment';

								$is_exist=isset($arr_qa_field[$field_name]);
								$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
								$field_checked=$is_exist?" checked='checked' ":'';
								$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
								$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');

								/* if($is_exist){
									echo __FILE__.__LINE__;var_dump($field_value_text);exit; //TODO testing
								} */

								$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
								$output.= "<td>".strip_tags($v_sub_question['question'])." - ".Baogg_Language::get('comment').": </td>";
								/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'check').'</td>';
								$output.= "<td><input type=\"text\" name=\"field_value[{$field_name}]\" value=\"$field_value_text\"  /></td>"; */
								$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(strip_tags($v_sub_question['question'])." - ".Baogg_Language::get('comment'))),($is_exist?$arr_qa_field[$field_name]:array())));
								$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";
							}
						}
						if($v['other']=='Y'){
							$field_name=$_field_name.'other';
								
							$is_exist=isset($arr_qa_field[$field_name]);
							$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
							$field_checked=$is_exist?" checked='checked' ":'';
							$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
							$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
								
							$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
							$output.= "<td>".Baogg_Language::get('other').": </td>";
							/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
							$output.= "<td><input type=\"text\" name=\"field_value[{$field_name}]\" value=\"{$field_value_text}\" /></td>"; */
							$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(Baogg_Language::get('other'))),($is_exist?$arr_qa_field[$field_name]:array())));
							$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";

							if($v['type']=='P'){
								$field_name.='comment';

								$is_exist=isset($arr_qa_field[$field_name]);
								$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
								$field_checked=$is_exist?" checked='checked' ":'';
								$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
								$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');


								$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
								$output.= "<td>".Baogg_Language::get('comment').": </td>";
								/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'check').'</td>';
								$output.= "<td><input type=\"text\" name=\"field_value[{$field_name}]\" value=\"{$field_value_text}\" /></td>"; */
								$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle(Baogg_Language::get('comment'))),($is_exist?$arr_qa_field[$field_name]:array())));
								$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";
							}
						}


						break;

						/*
						 * This question types use the default settings:
						* 	L - List (Radio)
						O - List With Comment
						! - List (Dropdown)
						*/
					default :
						$is_exist=isset($arr_qa_field[$field_name]);
					$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
					$field_checked=$is_exist?" checked='checked' ":'';
					$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
					$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
					$arr_field_value_text=explode(",",$field_value_text);

					$str_option='';
					$rs_answer=$Qa_Answers->getList(array('qid'=>(int)$v['qid'],'language'=>$language),array('sortorder','code'));
					foreach((array)$rs_answer as $v_sub_answer){
						$str_checked='';
						if(in_array($v_sub_answer['code'],$arr_field_value_text)){
							$str_checked=' selected="selected" ';
						}
						$str_option.="<option value=\"{$v_sub_answer['code']}\" {$str_checked}>".strip_tags($v_sub_answer['answer'])."</option>";
					}
					if(in_array($v['type'],array('L','!')) && $v['other']=='Y'){
						$str_checked='';
						if(in_array('-oth-',$arr_field_value_text)){
							$str_checked=' selected="selected" ';
						}
						$str_option.="<option value=\"-oth-\" {$str_checked}>".Baogg_Language::get('other')."</option>";
					}

					$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
					$output.= "<td>{$question_name}: </td>";
					/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected,'multi').'</td>';
					$output.= "<td><select name=\"field_value[$field_name][]\" multiple='multiple'>".$str_option."</select></td>"; */
					$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle($question_name)),($is_exist?$arr_qa_field[$field_name]:array())));

					if(in_array($v['type'],array('L','!')) && $v['other']=='Y'){
						$field_name=$_field_name.'other';

						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							
							
						$output.="</tr><tr  class=\"question  row".($i_row %2)."\" >";
						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
						$output.= "<td>{$question_name} - ".Baogg_Language::get('other').": </td>";
						/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_value_text).'</td>';
						$output.= "<td><input type=\"text\" name=\"field_value[{$field_name}]\" value=\"{$arr_field_value_text}\" /><td>"; */
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle("{$question_name} - ".Baogg_Language::get('other'))),($is_exist?$arr_qa_field[$field_name]:array())));
					}else if($v['type']=='O'){
						$field_name=$_field_name.'comment';
							
						$is_exist=isset($arr_qa_field[$field_name]);
						$is_exist_filter=$is_exist && isset($arr_qa_field[$field_name]['operation']);
						$field_checked=$is_exist?" checked='checked' ":'';
						$field_op_selected=($is_exist_filter?$arr_qa_field[$field_name]['operation']:null);
						$field_value_text=($is_exist_filter?$arr_qa_field[$field_name]['values']:'');
							
							
						$output.="</tr><tr  class=\"question  row".($i_row %2)."\"  >";
						$output .= "<td><input type='checkbox'  name='summary[]' value='$field_name' {$field_checked} /> </td>";
						$output.= "<td>{$question_name} - ".Baogg_Language::get('comment').": </td>";
						/* $output.='<td>'.Qa_Questions::genOp($field_name,$field_op_selected).'</td>';
						$output.= "<td><input type=\"text\" name=\"field_value[{$field_name}]\" value=\"{$field_value_text}\" /><td>"; */
						$output.= Qa_Questions::genAttr($field_name,array_merge(array( 'ordering'=>($i_index++)*10, 'qa_field_name'=>$this->trimTitle("{$question_name} - ".Baogg_Language::get('comment'))),($is_exist?$arr_qa_field[$field_name]:array())));
					}

					break;
				}

				//remove last blank <tr>
				$last_tr=strrpos($output,"<tr");
				$last_td=strrpos($output,"<td>");
				if($last_tr>$last_td){
					$output=substr($output,0,$last_tr);
				}else{
					$output.='</tr>';
				}


			}

		}


		if($this->getRequest()->isPost()){
				
				
			$arr_where=array();
			$arr_post=$this->getRequest()->getPost();
			$arr_field=(array)@$arr_post['summary'];
			$arr_exist_field=array();$arr_exist_filter=array();$arr_exist_list=array();$arr_exist_chart=array();$arr_exist_sort=array();
			foreach((array)$arr_field as $k=>$field_name){
				if(!isset($fieldmap[$field_name])){
					continue;
				}
				$v_qa_field=array();
				$v_qa_field['qa_field_name']=@$arr_post['field_title'][$field_name];
				$v_qa_field['qa_field_code']=$field_name;
				$v_qa_field['qa_surveys_id']=@$params['qa_surveys_id'];
				$v_qa_field['ordering']=@$arr_post['field_order'][$field_name];
				$v_qa_field['is_filter']=(int)@$arr_post['field_is_filter'][$field_name];
				$v_qa_field['is_list']=(int)@$arr_post['field_is_list'][$field_name];
				$v_qa_field['dict_id']=(int)@$arr_post['field_dict_id'][$field_name];
				$v_qa_field['is_chart']=(int)@$arr_post['field_is_chart'][$field_name];
				$v_qa_field['is_sort']=(int)@$arr_post['field_is_sort'][$field_name];
				if($rs_qa_field=$QaField->getList(array('qa_surveys_id'=>@$params['qa_surveys_id'],'qa_field_code'=>$field_name))){
					$qa_field_id=@$rs_qa_field[0]['qa_field_id'];
					$QaField->_update($v_qa_field,$qa_field_id);
				}else{
					$qa_field_id=$QaField->_insert($v_qa_field);
				}
				$arr_exist_field[]=$qa_field_id;


				//if is_filter(is_filter) is true,or having value or op is null,is not null
				/* $is_filter=@$arr_post['field_is_filter'][$field_name];
				$is_filter=$is_filter || (@$arr_post['field_op'][$field_name] &&  @$arr_post['field_value'][$field_name]!==null && @$arr_post['field_value'][$field_name]!=="");
				$is_filter=$is_filter || in_array($arr_post['field_op'][$field_name],array('is null','is not null'));
				if($is_filter ){
					$v_qa_filter=array();
					$v_qa_filter['qa_surveys_id']=@$params['qa_surveys_id'];
					$v_qa_filter['qa_field_id']=$qa_field_id;
					$v_qa_filter['operation']=@$arr_post['field_op'][$field_name];
						
					$v_values=(is_null(@$arr_post['field_value'][$field_name]) || in_array($arr_post['field_op'][$field_name],array('is null','is not null')))?'':@$arr_post['field_value'][$field_name];
						
					$v_qa_filter['values']=is_array($v_values)?implode(",",$v_values):$v_values;
						
					if($rs_qa_filter=$QaFilter->getList(array('qa_field_id'=>$qa_field_id))){
						$v_qa_filter_id=@$rs_qa_filter[0]['qa_filter_id'];
						$QaFilter->_update($v_qa_filter,$v_qa_filter_id);

					}else{						
						$v_qa_filter['ordering']=$v_qa_field['ordering'];
						$v_qa_filter_id=$QaFilter->_insert($v_qa_filter);
					}
					$arr_exist_filter[]=$qa_field_id;
				}
				

				//if is_list is true
				$is_list=@$arr_post['field_is_list'][$field_name];
				if($is_list){
					$v_qa_list=array();
					$v_qa_list['qa_surveys_id']=@$params['qa_surveys_id'];
					$v_qa_list['qa_field_id']=$qa_field_id;
					if($rs_qa_list=$QaList->getList(array('qa_field_id'=>$qa_field_id))){
						$v_qa_list_id=@$rs_qa_list[0]['qa_list_id'];
						$v_qa_list_id=@$rs_qa_list[0]['qa_list_id'];
						 $QaList->_update($v_qa_list,$v_qa_list_id);		
					}else{

						$v_qa_list['qa_list_name']=$v_qa_field['qa_field_name'];
						$v_qa_list['ordering']=$v_qa_field['ordering'];
						$v_qa_list_id=$QaList->_insert($v_qa_list);
					}
					$arr_exist_list[]=$qa_field_id;
				}
				


				//if is_chart is true
				$is_chart=@$arr_post['field_is_chart'][$field_name];
				if($is_chart){
					$v_qa_chart=array();
					$v_qa_chart['qa_surveys_id']=@$params['qa_surveys_id'];
					$v_qa_chart['qa_field_id']=$qa_field_id;
					if($rs_qa_chart=$QaChart->getList(array('qa_field_id'=>$qa_field_id))){
						$v_qa_chart_id=@$rs_qa_chart[0]['qa_chart_id'];
						$QaChart->_update($v_qa_chart,$v_qa_chart_id);
					}else{
						$v_qa_chart['qa_chart_name']=$v_qa_field['qa_field_name'];
						$v_qa_chart['ordering']=$v_qa_field['ordering'];
						$v_qa_chart_id=$QaChart->_insert($v_qa_chart);
					}
					$arr_exist_chart[]=$qa_field_id;
				}
				

				//if is_sort is true
				$is_sort=@$arr_post['field_is_sort'][$field_name];
				if($is_sort){
					$v_qa_sort=array();
					$v_qa_sort['qa_surveys_id']=@$params['qa_surveys_id'];
					$v_qa_sort['qa_field_id']=$qa_field_id;
					if($rs_qa_sort=$QaSort->getList(array('qa_field_id'=>$qa_field_id))){
						$v_qa_sort_id=@$rs_qa_sort[0]['qa_sort_id'];
						$QaSort->_update($v_qa_sort,$v_qa_sort_id);
					}else{
						$v_qa_sort['ordering']=$v_qa_field['ordering'];;
						$v_qa_sort_id=$QaSort->_insert($v_qa_sort);
					}
					
					$arr_exist_sort[]=$qa_field_id;
				}
				 */
					
			}
			
				
			/* $where_surveys=array('qa_surveys_id='.(int)$v_qa_field['qa_surveys_id']);
				
			$arr_exist_field=array_filter($arr_exist_field);
			$where=$arr_exist_field?array_merge($where_surveys,array('qa_field_id not in ('.implode(',',$arr_exist_field).')')):$where_surveys;
			$QaField->delete($where);
				
			$arr_exist_filter=array_filter($arr_exist_filter);
			$where=$arr_exist_filter?array_merge($where_surveys,array('qa_field_id not in ('.implode(',',$arr_exist_filter).')')):$where_surveys;				
			$QaFilter->delete($where);
				
			$arr_exist_list=array_filter($arr_exist_list);
			$where=$arr_exist_list?array_merge($where_surveys,array('qa_field_id not in ('.implode(',',$arr_exist_list).')')):$where_surveys;	
			//echo __FILE__.'<pre>';print_r($where);exit;			
			$QaList->delete($where);				
				
			$arr_exist_chart=array_filter($arr_exist_chart);
			$where=$arr_exist_chart?array_merge($where_surveys,array('qa_field_id not in ('.implode(',',$arr_exist_chart).')')):$where_surveys;				
			$QaChart->delete($where);			
				
			$arr_exist_sort=array_filter($arr_exist_sort);
			$where=$arr_exist_sort?array_merge($where_surveys,array('qa_field_id not in ('.implode(',',$arr_exist_sort).')')):$where_surveys;
			$QaSort->delete($where); */
				
				
				
				
			$ret=array("success"=>true,"msg"=>"save_ok");
			echo Baogg_Language::outputResult($ret);
			$this->_helper->viewRenderer->setNoRender ();
			//count number of answers
			/* $Qa_Survey=new Qa_Survey($survey_id);
			 $rs_total=$Qa_Survey->getList(array(),null,null,array('total'=>'count(*)'));
			$total=$rs_total[0]['total'];

			$rs_cnt=$Qa_Survey->getList($arr_where,null,null,array('cnt'=>'count(*)'));
			$cnt=$rs_cnt[0]['cnt']; */

				


		}

		$this->view->output=$output;
		$this->view->surveys="";
		$this->view->LANG=Zend_Json::encode($LANG);
		$next_step=$params;
		$next_step['action']='list2';
		$this->view->next_url=Baogg_Controller_Url::generate($next_step);
	}

	public function list3Action(){
		global $LANG;


		$QaField=new QaField();		
		$QaList=new QaList();		
		$QaChart=new QaChart();
		$QaFilter=new QaFilter();
		$QaSort=new QaSort();
		
		
		
		$params=$this->getRequest()->getParams();
		
		$QaField->refreshState($params['qa_surveys_id']);
		
		if ($this->getRequest()->isPost ())
		{
			//echo __FILE__.'<pre>';print_r($params);exit;
			
			if($params['task']=='save'){
				$ret=array('success'=>false,'msg'=>'save_fail');
				unset($params['qa_list_id']);
				unset($params['qa_chart_id']);
				unset($params['qa_filter_id']);
				unset($params['qa_sort_id']);
				
				$arr_add=array('list'=>array(),'chart'=>array(),'filter'=>array(),'sort'=>array());
				$arr_edit=array('list'=>array(),'chart'=>array(),'filter'=>array(),'sort'=>array());
				
				foreach((array)$params as $k=>$v){
					$arr_k=explode("_",$k);
					if($arr_k[0]=='add' && isset($arr_add[$arr_k[1]])){
						$table=$arr_k[1];						
						
						unset($arr_k[0]);unset($arr_k[1]);
						$col=implode('_',$arr_k);
						
						$arr_add[$table][$col]=$v;
						continue;						
					}else if(isset($arr_edit[$arr_k[0]])){
						$table=$arr_k[0];
						
						unset($arr_k[0]);
						$col=implode('_',$arr_k);
						foreach((array)$v as $key=>$field_value ){
							@$arr_edit[$table][$key][$col]=$field_value;
						}
					}
				}
				
				
				foreach((array)$arr_add as $table=>$row){
					if(!isset($row['qa_field_id']) || !$row['qa_field_id']){
						continue;
					}
					
					$class_name='Qa'.ucfirst($table);
					$instance=$$class_name;
					
					$row['qa_surveys_id']=$params['qa_surveys_id'];					
					$instance->_insert($row);

					
					try{						
						$QaField->_update(array('is_'.$table=>1),$row['qa_field_id']);
					}catch(Exception $e){
						echo '<pre>';print_r($arr_add);print_r($row);exit;
					}
				}
				
				
				
				foreach((array)$arr_edit as $table=>$arr_key){
					$class_name='Qa'.ucfirst($table);
					$instance=$$class_name;
					
					foreach((array)$arr_key as $key=>$row){
						$instance->_update($row,$key);
					}
				}
				
				
				//update qa_chart.type
				/* $Rule=new Rule();
				$rs_chart=$QaChart->getList(array('qa_surveys_id'=>$params['qa_surveys_id']));
				foreach((array)$rs_chart as $v){
					if(!$v['rule_id']){
						if($v['qa_chart_type']!=0){
							$QaChart->_update(array('qa_chart_type'=>0),$v['qa_chart_id']);
						}
					}else{
						$rs_rule=$Rule->getOne($v['rule_id']);
						if($v['qa_chart_type'] != $rs_rule[0]['is_group_by_fn']){
							$QaChart->_update(array('qa_chart_type'=>$rs_rule[0]['is_group_by_fn']),$v['qa_chart_id']);
						}
					}
					
				} */
				
				/* if($params['filter_field_id'] && $params['operation'] && $params['values']!==""){
					$arr_insert=$params;
					$arr_insert['qa_field_id']=$params['filter_field_id'];
					//echo __FILE__.__LINE__.'<pre>';print_r($arr_insert);exit;
					$QaFilter->_insert($arr_insert);
				}
				if($params['sort_field_id']){
					$arr_insert=$params;
					$arr_insert['qa_field_id']=$params['sort_field_id'];
					$arr_insert['ordering']=$params['sort_ordering'];
						
					$QaSort->_insert($arr_insert);
				}
				if($params['chart_field_id']){
					$arr_insert=$params;
					$arr_insert['qa_field_id']=$params['chart_field_id'];
					$arr_insert['ordering']=$params['chart_ordering'];
					$QaChart->_insert($arr_insert);
				} */
				
				
				$ret=array('success'=>true,'msg'=>'save_ok');
			}else if($params['task']=='delete'){
				
				$ret=array('success'=>false,'msg'=>'delete_fail');
				
				if(@$params['qa_list_id']){
					//get all field_id 
					/* $arr_field_id=array();
					$rs_list=$QaList->getList(array('qa_list_id'=>$params['qa_list_id']));					
					foreach((array)$rs_list as $v){
						$arr_field_id[]=$v['qa_field_id'];
					}	 */	
					
					$QaList->_delete($params['qa_list_id']);
					
					//get remained field_id
					/* $rs_list=$QaList->getList(array('qa_field_id'=>$arr_field_id));

					$arr_field_id && $QaField->_update(array('is_list'=>0),$arr_field_id); */
				}
				if(@$params['qa_filter_id']){
					
					/* $rs_filter=$QaFilter->getList(array('qa_filter_id'=>$params['qa_filter_id']));
					$arr_field_id=array();
					foreach((array)$rs_filter as $v){
						$arr_field_id[]=$v['qa_field_id'];
					}
					$arr_field_id && $QaField->_update(array('is_filter'=>0),$arr_field_id); */
					
					$QaFilter->_delete($params['qa_filter_id']);
				}
				if(@$params['qa_sort_id']){
					
					/* $rs_sort=$QaSort->getList(array('qa_sort_id'=>$params['qa_sort_id']));
					$arr_field_id=array();
					foreach((array)$rs_sort as $v){
						$arr_field_id[]=$v['qa_field_id'];
					}
					$arr_field_id && $QaField->_update(array('is_sort'=>0),$arr_field_id); */
					
					
					$QaSort->_delete($params['qa_sort_id']);
				}
				if(@$params['qa_chart_id']){
					
					/* $rs_chart=$QaChart->getList(array('qa_chart_id'=>$params['qa_chart_id']));
					$arr_field_id=array();
					foreach((array)$rs_chart as $v){
						$arr_field_id[]=$v['qa_field_id'];
					}
					$arr_field_id && $QaField->_update(array('is_chart'=>0),$arr_field_id); */						
										
					
					$QaChart->_delete($params['qa_chart_id']);
				}
				$ret=array('success'=>true,'msg'=>'delete_ok');
			}
				
			echo Baogg_Language::outputResult($ret);
				
			$this->_helper->viewRenderer->setNoRender ();
		}


		$arr_qa_field=$QaField->getArray(array('qa_surveys_id'=>@$params['qa_surveys_id']),array('sort'=>'ordering','dir'=>'asc'));
		$arr_field_label=array(0=>Baogg_Language::get('please_select'));
		foreach((array)$arr_qa_field as $k=>$v){
			$arr_field_label[$k]=$v['qa_field_name'];
		}
		
		$Rule=new Rule();
		$rs_rule=$Rule->getList(array('state'=>1,'rule_type_id'=>Rule::CMH_TYPE),array('sort'=>'ordering','dir'=>'asc'));
		$arr_rule_label=array(0=>Baogg_Language::get('please_select'));
		foreach((array)$rs_rule as $v){
			$arr_rule_label[$v['rule_id']]=$v['rule_name'];
		}
		
		$arr_state_label=Baogg_Language::get('arr_state');
		
		$arr_operation_label=Qa_Questions::getOps();
		$arr_operation_label=array_merge(array(''=>Baogg_Language::get('please_select')),$arr_operation_label);
		
		$arr_dir=array('asc','desc');
		$arr_dir_label=array_map(array('Baogg_Language','get'),$arr_dir);
		$arr_dir_label=array_combine($arr_dir,$arr_dir_label);
		
		$arr_axis_label=array('X'.Baogg_Language::get('axis'),'Y'.Baogg_Language::get('axis'));
		
		$Form=new Baogg_View_Form();
		
		$rs_qa_list=$QaList->getList(array('qa_surveys_id'=>@$params['qa_surveys_id']),array('sort'=>'ordering','dir'=>'asc'));
		foreach((array)$rs_qa_list as $k=>$v){
			$rs_qa_list[$k]['rule_id']=$Form->renderFormSelect(array('id'=>"list_rule_id[{$v['qa_list_id']}]",'tag'=>'select','data'=>$arr_rule_label,'selected'=>$v['rule_id']));
			$rs_qa_list[$k]['qa_list_name']=$Form->renderFormElement(array('id'=>"list_qa_list_name[{$v['qa_list_id']}]",'value'=>$v['qa_list_name']));
			$rs_qa_list[$k]['state']=$Form->renderFormRadio(array('id'=>"list_state[{$v['qa_list_id']}]",'tag'=>'radio','data'=>$arr_state_label,'selected'=>$v['state']));
			$rs_qa_list[$k]['ordering']=$Form->renderFormElement(array('id'=>"list_ordering[{$v['qa_list_id']}]",'value'=>$v['ordering']));
		}
		
		$rs_qa_chart =$QaChart->getList(array('qa_surveys_id'=>@$params['qa_surveys_id']),array('sort'=>'ordering','dir'=>'asc'));
		foreach((array)$rs_qa_chart as $k=>$v){
			$rs_qa_chart[$k]['qa_chart_type']=$Form->renderFormSelect(array('id'=>"chart_qa_chart_type[{$v['qa_chart_id']}]",'tag'=>'select','data'=>$arr_axis_label,'selected'=>$v['qa_chart_type']));
			$rs_qa_chart[$k]['rule_id']=$Form->renderFormSelect(array('id'=>"chart_rule_id[{$v['qa_chart_id']}]",'tag'=>'select','data'=>$arr_rule_label,'selected'=>$v['rule_id']));
			$rs_qa_chart[$k]['qa_chart_name']=$Form->renderFormElement(array('id'=>"chart_qa_chart_name[{$v['qa_chart_id']}]",'value'=>$v['qa_chart_name']));
			$rs_qa_chart[$k]['ordering']=$Form->renderFormElement(array('id'=>"chart_ordering[{$v['qa_chart_id']}]",'value'=>$v['ordering']));
		}
		
		$rs_qa_filter=$QaFilter->getList(array('qa_surveys_id'=>@$params['qa_surveys_id']),array('sort'=>'ordering','dir'=>'asc'));
		foreach((array)$rs_qa_filter as $k=>$v){			
			$rs_qa_filter[$k]['operation']=$Form->renderFormSelect(array('id'=>"filter_operation[{$v['qa_filter_id']}]",'tag'=>'select','data'=>$arr_operation_label,'selected'=>$v['operation']));
			$rs_qa_filter[$k]['values']=$Form->renderFormElement(array('id'=>"filter_values[{$v['qa_filter_id']}]",'value'=>$v['values']));
			$rs_qa_filter[$k]['state']=$Form->renderFormRadio(array('id'=>"filter_state[{$v['qa_filter_id']}]",'tag'=>'radio','data'=>$arr_state_label,'selected'=>$v['state']));
			$rs_qa_filter[$k]['ordering']=$Form->renderFormElement(array('id'=>"filter_ordering[{$v['qa_filter_id']}]",'value'=>$v['ordering']));
		}
		
		$rs_qa_sort =$QaSort->getList(array('qa_surveys_id'=>@$params['qa_surveys_id']),array('sort'=>'ordering','dir'=>'asc'));
		foreach((array)$rs_qa_sort as $k=>$v){
			$rs_qa_sort[$k]['dir']=$Form->renderFormSelect(array('id'=>"sort_dir[{$v['qa_sort_id']}]",'tag'=>'select','data'=>$arr_dir_label,'selected'=>$v['dir']));			
			$rs_qa_sort[$k]['ordering']=$Form->renderFormElement(array('id'=>"sort_ordering[{$v['qa_sort_id']}]",'value'=>$v['ordering']));
		}
		

		
		$this->view->arr_rule=$rs_rule;
		$this->view->arr_field=$arr_qa_field;
		$this->view->arr_operation=$arr_operation_label;
		$this->view->arr_state=$arr_state_label;
		
		$this->view->arr_list=$rs_qa_list;
		$this->view->arr_filter=$rs_qa_filter;
		$this->view->arr_sort=$rs_qa_sort;
		$this->view->arr_chart=$rs_qa_chart;
		


		$this->view->JSLANG=Zend_Json::encode($LANG);
		$this->view->LANG=$LANG;
		$this->view->output='';
	}
	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;

		$params=$this->getRequest()->getParams();
		$form_url=$params;

		Zend_Loader::loadClass("Baogg_View_Extgrid");

		$cm=array();
		$cm['qa_surveys_id']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_PK) ;
		$cm['qa_surveys_name']=array("sortable"=>true);
		$cm['survey_id']=array("hidden"=>true);
		$cm['survey_name']=array("hidden"=>true);
		$cm['ordering']=array("sortable"=>true);
		$cm['state']=array("sortable"=>true);
		//$cm['action']=array("sortable"=>false);
		//$cm['ordering']=array("sortable"=>true);
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;

		$form_url['action']="data";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);
		$grid->addExistButtons(array('add','remove','query'),array('edit','delete'));
		//$grid->registerButton("fields","window.location.href='".BAOGG_BASE_URL."dict/levelfield/list/';");

		$this->view->form_url=BAOGG_BASE_URL."dict/level/save";
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();

		$form_url['action']='add';
		$form=new Baogg_View_Extform(array("url"=>$form_url,"height"=>300,"width"=>600));

		$Qa_Surveys=new Qa_Surveys();
		$store_survey=$Qa_Surveys->getCombo(null,null,null,array('sid'),array(array('name'=>'surveys_languagesettings','condition'=>'surveys.sid=surveys_languagesettings.surveyls_survey_id and surveyls_language=\'zh-Hans\'','cols'=>array('surveyls_title'))));
		//echo '<pre>';print_r($store_survey);exit;

		$form->addItem(0,array('name'=>'qa_surveys_name'));
		$form->addItem(0,array('name'=>'survey_id','xtype'=>'combo','store'=>$store_survey));
		$form->addItem(1,array('name'=>'ordering'));
		$form->addItem(2,array('name'=>'state','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		$form->addItem(2,array('name'=>'qa_surveys_id',"xtype"=>"hidden","hideLabel"=>true));
		$form->addExistButtons(array('-','save_grid','save_new','save','-','search','-','cancel'));//,'config','config'

		//$form->addExistButtons(array('search','add','edit','delete','remove','reset'),array('edit','delete'));


		$this->view->form=$form;

		//echo '<pre>';var_dump($LANG);exit;


	}

	/**
	 * The data action
	 */
	function dataAction() {
		global $LANG;

		$QaSurveys=new QaSurveys();
		$post=$this->_request->getPost ();
		$where=array();$order=array();$limit=array();
		foreach((array)$post as $k=>$v){
			if($k=="start" || $k=="limit"){
				$limit[$k]=$v;
			}else if($k=="sort" || $k=="dir"){
				$order[$k]=$v;
			}else{
				if($k=="qa_surveys_id"  ){
					if($v && is_numeric($v)){
						$v=(int)$v;
						$where[$k]=$v;
					}
				}else{
					$v='%'.$v.'%';
					$where[$k]=$v;
				}

			}
		}

		$rs=$QaSurveys->getList($where,$order,$limit);
		$rs_cnt=$QaSurveys->getList($where,NULL,NULL,"count(*) as cnt");
		echo  Zend_Json::encode(array("count"=>$rs_cnt[0]['cnt'],"data"=>$rs));
		Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);
	}


	/**
	 * The add action
	 */
	function addAction(){
		$this->saveAction();
	}

	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();
	}


	/**
	 * The delete action
	 */
	function deleteAction() {
		$Qa_Report=new Qa_Report();
		$ret=array("success"=>false,"msg"=>"delete_fail");
		$id = Baogg_Controller_Action::_getParam ( 'ids' );
			
		$Qa_Surveys=new Qa_Surveys();

		if ($Qa_Surveys->_delete ( $id )){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}

		echo Baogg_Language::outputResult($ret);
		$this->_helper->viewRenderer->setNoRender ();
	}

	function removeAction(){
		$this->deleteAction();
	}

	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;

		$ret=array("success"=>false,"msg"=>"save_fail");
			
		$QaSurveys=new QaSurveys();
		//check form
		if (!$this->_request->isPost ())
		{
			echo Baogg_Language::outputResult($ret);
			exit;
		}

		$formData = $this->_request->getPost ();

		if(!$formData)
		{
			echo Baogg_Language::outputResult($ret);
			exit;
		}
			
		$arr=$QaSurveys->filterForm($formData);
		$action=$this->getRequest()->getParam('action');
		$rs = $QaSurveys->getSame($arr);

		if($action=='edit'){
			if(count($rs)==0 || count($rs)==1 &&  $rs[0] == $arr["qa_surveys_id"] ){
				$QaSurveys->_update($arr,$arr["qa_surveys_id"]);
				$ret['success'] = true;
				$ret['msg'] = "save_ok";
			}else{
				$ret['msg'] = "exist_same_record";
			}

		}else{
			//insert record
			//$permission_type = 1;
			if($rs){
				$ret['msg'] = "exist_same_record";
			}else{
				unset($arr["qa_surveys_id"]);
				$ret['success'] = $QaSurveys->_insert($arr)>0?true:false;
				$ret['msg'] = "add_ok";
			}
		}

		echo Baogg_Language::outputResult($ret);

		$this->_helper->viewRenderer->setNoRender ();


	}

	private function trimTitle($string){
		$string=str_replace(array('&nbsp;'),array(' '),$string);
		$string=  trim(mb_ereg_replace('[^\u4e00-\u9fa5\w]+', '_', $string),'_0123456789 ');
		if(strpos($string,'nbsp;')===0){
			$string=substr($string, 5);
		}
		return $string;
	}
}
